from flask_restx import Resource
from flask import request
from api import ns
from models.database import get_db_connection
from utils.auth import token_required
import uuid
from datetime import datetime, timedelta

@ns.route('/share')
class ShareController(Resource):
    @token_required
    def post(self):
        """创建分享"""
        try:
            user_id = request.user.get('user_id')
            data = request.get_json()
            
            if not data or 'history_id' not in data:
                return {'status': 'error', 'message': '缺少必要参数'}, 400
            
            conn = get_db_connection()
            cursor = conn.cursor()
            
            # 获取生成记录信息
            cursor.execute("""
                SELECT 
                    prompt_text, 
                    style, 
                    output_url, 
                    created_at
                FROM history
                WHERE history_id = %s AND user_id = %s
            """, (data['history_id'], user_id))
            
            record = cursor.fetchone()
            if not record:
                return {'status': 'error', 'message': '记录不存在'}, 404
            
            # 创建分享记录
            share_id = str(uuid.uuid4())
            cursor.execute("""
                INSERT INTO shares (
                    share_id, user_id, history_id, 
                    text, style, image_url, 
                    created_at, expires_at
                ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            """, (
                share_id,
                user_id,
                data['history_id'],
                record[0],  # text
                record[1],  # style
                record[2] or record[3],  # 优先使用原始URL
                datetime.now(),
                datetime.now() + timedelta(days=30)  # 30天后过期
            ))
            
            conn.commit()
            
            share_url = f"/share/{share_id}"
            return {
                'status': 'success',
                'message': '创建分享成功',
                'data': {
                    'share_id': share_id,
                    'share_url': share_url
                }
            }
            
        except Exception as e:
            print(f"Error creating share: {str(e)}")
            return {'status': 'error', 'message': '创建分享失败'}, 500
        finally:
            if conn:
                conn.close()

    def get(self):
        """获取分享信息"""
        try:
            share_id = request.args.get('id')
            if not share_id:
                return {'status': 'error', 'message': '缺少分享ID'}, 400
            
            conn = get_db_connection()
            cursor = conn.cursor()
            
            cursor.execute("""
                SELECT s.*, u.username, u.nickname, u.avatar_url
                FROM shares s
                LEFT JOIN users u ON s.user_id = u.id
                WHERE s.share_id = %s AND s.expires_at > NOW()
            """, (share_id,))
            
            share = cursor.fetchone()
            if not share:
                return {'status': 'error', 'message': '分享不存在或已过期'}, 404
            
            return {
                'status': 'success',
                'data': {
                    'share_id': share[0],
                    'text': share[3],
                    'style': share[4],
                    'image_url': share[5],
                    'created_at': share[6].strftime('%Y-%m-%d %H:%M:%S'),
                    'expires_at': share[7].strftime('%Y-%m-%d %H:%M:%S'),
                    'creator': {
                        'username': share[9],
                        'nickname': share[10],
                        'avatar': share[11]
                    }
                }
            }
            
        except Exception as e:
            print(f"Error getting share: {str(e)}")
            return {'status': 'error', 'message': '获取分享信息失败'}, 500
        finally:
            if conn:
                conn.close() 